package com.lcj.ai.config;

import cn.hutool.core.lang.UUID;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * <p>
 *
 * </p>
 *
 * @author: liuchangjun
 * @since: 2024/1/3 10:09
 */
@Component
public class TraceIdInterceptor implements HandlerInterceptor {
    /**
     * 日志跟踪id
     */
    private final static String TRACE_ID = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = getTraceId(request);
        MDC.put(TRACE_ID, traceId);
        // 将traceId添加进响应头
        response.addHeader(TRACE_ID,traceId);
        return true;
    }

    private String getTraceId(HttpServletRequest request){
        return String.format("%s - %s",request.getRequestURI(), UUID.randomUUID().toString());
    }
}
